package org.breathe.command.impl.hash;

import org.breathe.command.Command;
import org.breathe.command.CommandType;
import org.breathe.datastruct.RedisBytes;
import org.breathe.datastruct.RedisData;
import org.breathe.datastruct.impl.RedisHash;
import org.breathe.protocal.Resp;
import org.breathe.protocal.decode.BulkString;
import org.breathe.protocal.decode.Errors;
import org.breathe.protocal.decode.RespInteger;
import org.breathe.server.core.RedisCore;

import java.util.List;
import java.util.stream.Stream;

/**
 * @author: breathe
 * @createTime: 2025-05-15
 */
public class HDel implements Command {
    private RedisCore redisCore;
    private RedisBytes key;
    private List<RedisBytes> fields;
    public HDel(RedisCore redisCore) {
        this.redisCore = redisCore;
    }

    @Override
    public CommandType getType() {
        return CommandType.HDEL;
    }

    @Override
    public void setContext(Resp[] array) {
        if (array.length < 3) {
            throw new IllegalArgumentException("argument error");
        }
        key = ((BulkString)array[1]).getContent();
        fields = Stream.of(array)
                .skip(2)
                .map(BulkString.class::cast)
                .map(BulkString::getContent)
                .toList();
    }

    @Override
    public Resp handle() {
        RedisData redisData = redisCore.get(key);
        if (redisData == null) {
            return new BulkString("0");
        }
        if (redisData instanceof RedisHash redisHash) {
            return new RespInteger(redisHash.delete(fields));
        }
        return new Errors("argument error");
    }

    @Override
    public boolean writeCommand() {
        return true;
    }
}
